﻿
// First: Create config
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null,
    decorateElement: true,
    errorClass: "error",
    errorMessageClass: "error-desc"
});

// Second: Create new model to apply to view
var viewModel = new function () {
    this.ProductGroup = ko.observable();
    this.ProductGroupOptions = ko.observableArray(data.ListProductGroup);

    // About you
    this.Name = ko.observable().extend({ maxLength: 50 }).extend({ required: { message: "Name is required"} });
    this.ShortDesc = ko.observable().extend({ maxLength: 50 }).extend({ required: { message: "Short Desc is required"} });
    this.LongDesc = ko.observable();
    this.Price = ko.observable();
    this.UnitPrice = ko.observable();
    this.LongTimeValue = ko.observable();
    this.LongTimeUnit = ko.observable();
    this.IsDefault = ko.observable(false);
    this.Active = ko.observable(false);

    // Submit, Next button
    this.InvalidateForm = ko.observable(false);
    this.SubmitForm = function () {
        if (viewModel.errors().length == 0) {
            $('form').submit();
        }
        else {
            viewModel.errors.showAllMessages();
            this.InvalidateForm(true);
        }
    }
};

viewModel.errors = ko.validation.group(viewModel);

// Third: Apply view model to view to handle action when user input data
ko.validation.rules.pattern.message = 'Invalid.';
ko.applyBindings(viewModel, document.getElementById("main"));